package com.pyl.admin.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pyl.admin.core.enums.ResultEnum;
import com.pyl.admin.core.enums.StatusEnum;
import com.pyl.admin.core.exception.ResultException;
import com.pyl.admin.core.shiro.ShiroUtil;
import com.pyl.admin.system.entity.SysDept;
import com.pyl.admin.system.entity.SysUser;
import com.pyl.admin.system.mapper.SysDeptMapper;
import com.pyl.admin.system.mapper.SysUserMapper;
import com.pyl.admin.system.service.SysDeptService;
import com.pyl.admin.system.validator.DeptForm;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 灵魂贰婶
 * @since 2019-06-28
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

	@Autowired
	private SysDeptMapper sysDeptMapper;

	@Autowired
	private SysUserMapper sysUserMapper;

	@Override
	public List<SysDept> selectDeptList(Integer status, String title) {
		return sysDeptMapper.selectDeptList(status, title);
	}

	@Override
	@Transactional
	public boolean saveOrUpdate(DeptForm deptForm) {
		// 添加全部上级序号
		if (deptForm.getPid() != 0) {
			SysDept pDept = sysDeptMapper.selectById(deptForm.getPid());
			deptForm.setPids(pDept.getPids() + ",[" + deptForm.getPid() + "]");
		} else {
			deptForm.setPids("[0]");
		}
		if (deptForm.getId() == null) {
			// 排序为空时，添加到最后
			SysDept sysDept = new SysDept();
			BeanUtil.copyProperties(deptForm, sysDept, CopyOptions.create().setIgnoreNullValue(true));
			sysDept.setCreateBy(ShiroUtil.getSubject().getId());
			sysDept.setCreateByName(ShiroUtil.getSubject().getNickname());
			sysDept.setCreateDate(new Date());
			sysDept.setStatus(Integer.valueOf(StatusEnum.OK.getCode()));
			sysDept.setUpdateBy(ShiroUtil.getSubject().getId());
			sysDept.setUpdateByName(ShiroUtil.getSubject().getNickname());
			sysDept.setUpdateDate(new Date());
			List<SysDept> sysDepts = sysDeptMapper.restOrderby(deptForm.getPid(), deptForm.getSort(), null, null);
			if (CollectionUtil.isNotEmpty(sysDepts)) {
				sysDept.setSort(deptForm.getSort() == 0 ? 1 : deptForm.getSort() + 1);
				for (int i = 0; i < sysDepts.size(); i++) {
					sysDeptMapper.updateById(sysDepts.get(i).setSort(sysDepts.get(i).getSort() + 1));
				}
			} else { // 排在最后面
				Integer sortMax = sysDeptMapper.selectSortMax(deptForm.getPid());
				if (ObjectUtil.isNotNull(sortMax)) {
					sysDept.setSort(sortMax + 1);
				}else {
					sysDept.setSort(1);
				}
			}
			return SqlHelper.retBool(sysDeptMapper.insert(sysDept));

		}

		// 更新 获取兄弟节点
		List<SysDept> sysDepts = sysDeptMapper.selectList(new EntityWrapper<SysDept>().eq("pid", deptForm.getPid())
				.ne("id", deptForm.getId()).orderAsc(Arrays.asList("sort")));

		SysDept sysDept = sysDeptMapper.selectById(deptForm.getId());
		BeanUtil.copyProperties(deptForm, sysDept, CopyOptions.create().setIgnoreNullValue(true));
		sysDept.setUpdateBy(ShiroUtil.getSubject().getId());
		sysDept.setUpdateByName(ShiroUtil.getSubject().getNickname());
		sysDept.setUpdateDate(new Date());
		// 设置排序
		sysDepts.add(deptForm.getSort(), sysDept);
		for (int i = 0; i < sysDepts.size(); i++) {
			SysDept dept = sysDepts.get(i);
			dept.setSort(i + 1);
			dept.setUpdateBy(ShiroUtil.getSubject().getId());
			dept.setUpdateByName(ShiroUtil.getSubject().getNickname());
			dept.setUpdateDate(new Date());
			sysDeptMapper.updateById(dept);
		}
		return true;
	}

	@Override
	@Transactional
	public boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {

		for (int i = 0; i < idList.size(); i++) {
			SysDept dept = sysDeptMapper.selectById(idList.get(i));
			// 是否有子项
			List<SysDept> childDepts = sysDeptMapper.selectList(new EntityWrapper<SysDept>().eq("pid", dept.getId())
					.eq("status", Integer.valueOf(StatusEnum.OK.getCode())));
			if (CollectionUtil.isNotEmpty(childDepts)) {
				throw new ResultException(ResultEnum.HAVE_CHILD_DEPT);
			}

			// 获取兄弟节点
			List<SysDept> brotherDept = new ArrayList<SysDept>();
			brotherDept = sysDeptMapper
					.selectList(new EntityWrapper<SysDept>().eq("pid", dept.getPid()).ne("id", dept.getId())
							.eq("status", Integer.valueOf(StatusEnum.OK.getCode())).orderAsc(Arrays.asList("sort")));

			dept.setStatus(Integer.valueOf(statusEnum.getCode()));
			dept.setUpdateBy(ShiroUtil.getSubject().getId());
			dept.setUpdateByName(ShiroUtil.getSubject().getNickname());
			dept.setUpdateDate(new Date());
			// 判断是 启用还是 删除冻结
			if (statusEnum == StatusEnum.OK) {
				brotherDept.add(dept.getSort() - 1, dept);
			} else if (statusEnum == StatusEnum.FREEZED || statusEnum == StatusEnum.DELETE) {
				// 判断是否有正常用户
				List<SysUser> sysUsers = sysUserMapper.selectList(new EntityWrapper<SysUser>()
						.eq("dept_id", dept.getId()).eq("status", Integer.valueOf(StatusEnum.OK.getCode())));
				if (CollectionUtil.isNotEmpty(sysUsers)) {
					throw new ResultException(ResultEnum.HAVE_USERS);
				}
				sysDeptMapper.updateById(dept);
			}
			// 重新排序
			if (CollectionUtil.isNotEmpty(brotherDept)) {
				for (int j = 0; j < brotherDept.size(); j++) {
					SysDept sysDept = brotherDept.get(j);
					sysDept.setUpdateBy(ShiroUtil.getSubject().getId());
					sysDept.setUpdateByName(ShiroUtil.getSubject().getNickname());
					sysDept.setUpdateDate(new Date());
					sysDept.setSort(j + 1);
					sysDeptMapper.updateById(sysDept);
				}
			}
		}
		return true;
	}

}
